<template>
	<div class="login">
		<div class="login01">
			<router-link to="/login">登录\</router-link>
			<router-link to="/enroll">注册</router-link>
		</div>
		<router-view />
		<van-form @submit="onSubmit">
			<van-field v-model="username" name="username" label="用户名" placeholder="用户名"
				:rules="[{ required: true, message: '请填写用户名' },
				{ pattern:/^1[3-9]\d{9}$/,message: '格式错误'}]" />
			<van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
				:rules="[{ required: true, message: '请填写密码' },
				{ validator:((val)=> /^\w{6,12}$/.test(val)), message: '密码格式错误' }]" />
			<div style="margin: 16px;">
				<van-button round block type="info" native-type="submit">登录</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
	import {loginApi} from "@/api/user.js"
	import {mapMutations} from 'vuex'
	export default {
		data() {
			return {
				username: '',
				password: '123456',
			};
		},
		methods: { 
			...mapMutations('UESR',['CHANGE_LOGIN_STATE','SET_TOKEN','SET_USERINFO','SET_UID']),
			onSubmit(values) {
				console.log('submit', values);
				loginApi(values).then(res=>{
					console.log(res)
					if(res.code==0){
						this.$toast(res.msg)
						let{uid,token,tokenExpired,userInfo}=res;
						localStorage.setItem('token',token)
						localStorage.setItem('tokenExpired',tokenExpired)
						
						this.CHANGE_LOGIN_STATE(true)
						this.SET_TOKEN(token)
						this.SET_USERINFO(userInfo)
						this.SET_UID(uid)
						
						setTimeout(v=>{
							this.$router.back()
						},500)
					}else{
						this.$toast(res.data.msg)
					}
				})
			},
		},
	};
</script>

<style>
	.login01 {
		background-color: #e54b43;
		height: 40px;
		text-align: center;
	}

	.login01 a {
		color: #fff;
		line-height: 40px;
	}
</style>
